import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {
  AtForm,
  AtInput,
  AtIcon, AtListItem, AtList, AtSwitch, AtModal, AtModalHeader, AtModalAction
} from 'taro-ui';
import {View, Text, Picker, Button, Image, ScrollView} from '@tarojs/components';
import './info.scss';
import {DateType} from '../../reducers/select-date';
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {
  BASE_URL,
  RESOURCE_URL,
  TEAM_APPOINT_ORDER_SETTING,
  UPLODE_FALE,
  TEAM_APPOINT_ORDER_CREATE, TARO_ENV, materialMedia,
} from "../../constants/api";
import {http} from "../../utils/http";
import {vcmonitor} from "../../utils/tools";
import {user} from "../../utils/user.service";
import {platform} from "../../utils/platform-settting.service";
import {h5Wx} from "../../utils/h5.service";
import {newHttp} from "../../utils/request";
import {lxH5Wx} from "../../utils/lx.h5.service";
import {getContent} from "../../utils/handlerPublicCode";

interface StateType {
  minHeight: any
  checkUserInput: any
  formData: any
  goodsMap: any
  teamAppoint: any
  map: any
  tableFile: string
  imgFile: string
  infoItemDetail: any
  fieldCustom: any
  radioStatus: number
  isOpened: boolean
  delModal: boolean
  custom_in_type: any
  tableName: string
}

type PageStateProps = {
  selectDate: DateType
}

type PageDispatchProps = {}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Confirm {
  props: IProps
}


class Confirm extends Component {
  state: StateType = {
    minHeight: 0,
    checkUserInput: {
      linkman: '请输入领队姓名',
      link_phone: '请输入领队电话',
      reserve_date: '请输入预约日期',
      custom_num: '请输入预约人数',
      team_org: '请输入组团单位',
      guide_num: '请输入讲解员人数',
      team_address: '请输入客源地',
      in_date: '请输入入场时间'
    },
    formData: {
      referSellerId: '',
      tempSellerId: '',
      goodsId: '',
      reserve_date: '',
      in_date: '',
      linkman: '',
      link_phone: '',
      team_org: '',
      team_address: '',
      is_reserve_meal: false,
      guide_num: '',
      custom_num: '',
      custom_in_type: '',
      customItemPic: [],
      info_item_detail: [],
      userUUID: ''
    },
    tableFile: '',
    imgFile: '',
    infoItemDetail: {},
    fieldCustom: [],
    teamAppoint: [],
    radioStatus: 0,
    goodsMap: {},
    map: {},
    isOpened: false,
    delModal: false,
    custom_in_type: 0,
    tableName: ''
  }
  goodsId = ''

  componentWillUnmount() {
    this.setState({isOpened: false})
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const platformSet = await platform.getSetting()
    if (platformSet.platformName) {
      Taro.setNavigationBarTitle({
        title: platformSet.platformName
      })
    }
    Taro.getSystemInfo({
      success: (res) => {
        this.setState({minHeight: res.windowHeight / 2 - 60})
      }
    })
  }

  async componentDidShow() {
    vcmonitor(this);
    let teamAppoint = Taro.getStorageSync('teamAppoint')
    teamAppoint = teamAppoint ? JSON.parse(teamAppoint) : []
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/my/index/index'})
      }, 1500)
      return
    }
    const {itemId, tempSellerId = ''} = Taro.getCurrentInstance().router.params
    this.goodsId = itemId
    if (!this.goodsId) {
      Taro.showToast({
        title: '参数错误',
        icon: 'none'
      })
      Taro.navigateBack()
      return false
    }
    const referSellerId = Taro.getStorageSync('bindSellerId') || 0
    const userData = await user.getUserData()
    const data = await http.carGet(TEAM_APPOINT_ORDER_SETTING, {goodsId: this.goodsId})
    const infoItemDetail = JSON.parse(data.map.info_item_detail)
    data.map.info_item_detail = infoItemDetail
    data.map.indate_end = data.map.indate_end.split('.')[0]
    data.map.indate_start = data.map.indate_start.split('.')[0]
    const fieldCustom = []
    for (const k in infoItemDetail) {
      if (k.includes('field')) {
        fieldCustom.push({k: infoItemDetail[k].k, ckd: infoItemDetail[k].ckd, name: k})
      }
    }
    const {formData} = this.state
    formData['referSellerId'] = referSellerId
    formData['tempSellerId'] = tempSellerId
    formData['userUUID'] = userData.uuid
    formData['goodsId'] = itemId
    if (data.user) {
      if (data.user.real_name) {
        formData['linkman'] = data.user.real_name
      }
      if (data.user.phone) {
        formData['link_phone'] = data.user.phone
      }
    }
    this.setState({
      goodsMap: data.goodsMap,
      map: data.map,
      infoItemDetail,
      fieldCustom,
      formData,
      teamAppoint
    })
    if (data.map.attention_need && data.map.attention_need !== '' && this.count === 0) {
      ++this.count
      this.setState({
        isOpened: true
      })
    }
  }

  count = 0

  personInput(val, e) {
    const {formData} = this.state
    if (val === 'reserve_date' || val === 'in_date') {
      formData[val] = e.detail.value
    } else {
      formData[val] = e
    }
    this.setState({formData})
  }

  changeRadioStatus(field) {
    const {radioStatus} = this.state
    if (radioStatus === field) {
      return
    }
    this.setState({radioStatus: field})
  }

  jumpEdit(val) {
    Taro.navigateTo({url: '/other/teamappoint/addcontact'})
  }

  downLoadFile() {
    // Taro.downloadFile({
    //   url: 'https://resource.ivcheng.com/upload/file/fbbac1ea6ef9486a8b88b912f7e72759.xlsx',
    //   success: function (res) {
    //     const filePath = res.tempFilePath
    //     Taro.openDocument({
    //       filePath: filePath,
    //       success: function (res) {
    //       }
    //     })
    //   }
    // })
    Taro.navigateTo({
      url: '/other/teamappoint/formGuide?page=table'
    })
  }

  async confirmReserve() {
    try {
      const {formData, radioStatus, map, imgFile, tableFile, checkUserInput} = this.state
      const info = map.info_item_detail
      for (const item in info) {
        if (info[item]) {
          if (item.indexOf('field') > -1) {
            if (info[item].ckd && (formData[item] === null || formData[item] === undefined || formData[item] === '')) {
              Taro.showToast({
                title: '请填写必填项',
                icon: 'none',
              })
              return
            }
          } else {
            if (formData[item] === null || formData[item] === undefined || formData[item] === '') {
              Taro.showToast({
                title: checkUserInput[item],
                icon: 'none',
              })
              return
            }
          }
        }
      }
      formData['custom_in_type'] = this.state.custom_in_type
      formData['info_item_detail'] = []
      Object.keys(formData).map(item => {
        if (item.indexOf('field') >= 0) {
          formData['info_item_detail'].push({
            key: item,
            value: formData[item],
            title: info[item].k,
            require: info[item].ckd || false
          });
        }
      })
      formData['info_item_detail'] = JSON.stringify(formData['info_item_detail'])
      formData['is_reserve_meal'] = Number(formData['is_reserve_meal'])
      if (radioStatus == 1) {
        if (imgFile) {
          formData['custom_item_pic'] = imgFile
        } else if (tableFile) {
          formData['custom_item_pic'] = tableFile
        }
      }
      if (radioStatus === 0) {
        let teamAppoint = Taro.getStorageSync('teamAppoint')
        teamAppoint = teamAppoint ? JSON.parse(teamAppoint) : []
        formData['custom_item_detail'] = JSON.stringify(teamAppoint)
      }
      Taro.showLoading({title: '提交中...'})
      const data = await http.postCar(TEAM_APPOINT_ORDER_CREATE + formData['userUUID'], formData)
      if (!data) {
        return
      }
      Taro.navigateTo({
        url: '/other/teamappoint/success'
      })
      Taro.removeStorageSync('teamAppoint')
      Taro.hideLoading()
    } catch (e) {
      Taro.hideLoading()
    }
  }

  uploadFile(val) {
    const api = BASE_URL + UPLODE_FALE
    const that = this
    this.setState({
      custom_in_type: val
    });
    if (TARO_ENV === 'h5') {
      if (process.env.P_ENV === 'lx') {
        lxH5Wx.chooseImage(async (files, length) => {
          lxH5Wx.uploadFile(files, length, (url) => {
            that.setState({imgFile: url})
          })
        }, 1)
      } else {
        h5Wx.chooseImage(1, async ret => {
          Taro.showToast({
            title: '正在上传...',
            icon: 'loading',
            mask: true,
            duration: 10000
          })
          h5Wx.wxuploadImage(ret, async res => {
            const data = await newHttp.catchGet(materialMedia + res, {})
            this.setState({imgFile: data})
            Taro.hideToast();
          })
        })
      }
      return
    }
    if (val === 1) {
      Taro.chooseImage({
        count: 1,  //最多可以选择的图片总数
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: (res) => {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFilePaths;
          //启动上传等待中...
          Taro.showToast({
            title: '正在上传...',
            icon: 'loading',
            mask: true,
            duration: 10000
          })
          let uploadImgCount = 0;
          for (let i = 0, h = tempFilePaths.length; i < h; i++) {
            Taro.uploadFile({
              url: api,
              filePath: tempFilePaths[i],
              name: 'file',
              formData: {
                'imgIndex': i
              },
              header: http.getHeader(),
              success: function (res) {
                uploadImgCount++;
                const data = JSON.parse(res.data);
                if (res.statusCode == 400) {
                  Taro.showToast({
                    title: data.message,
                    icon: 'none'
                  })
                  return
                }
                Taro.showToast({
                  title: '上传成功',
                  icon: 'none'
                })
                that.setState({imgFile: data.imageUrl, tableFile: null})
                //如果是最后一张,则隐藏等待中
                if (uploadImgCount == tempFilePaths.length) {
                  setTimeout(() => {
                    Taro.hideToast();
                  }, 2000)
                }
              },
              fail: function (res) {
                Taro.hideToast();
                Taro.showModal({
                  title: '错误提示',
                  content: '上传图片失败',
                  showCancel: false,
                  success: function (res) {
                  }
                })
              }
            });
          }
        }
      })
    } else {
      wx.chooseMessageFile({
        count: 1,
        type: "all",
        success(res) {
          that.setState({
            tableName: res.tempFiles[0].name
          });
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFiles;
          //启动上传等待中...
          Taro.showToast({
            title: '正在上传...',
            icon: 'loading',
            mask: true,
            duration: 10000
          })
          let uploadImgCount = 0;
          for (let i = 0, h = tempFilePaths.length; i < h; i++) {
            Taro.uploadFile({
              url: api,
              filePath: tempFilePaths[i].path,
              name: 'file',
              formData: {
                'imgIndex': i
              },
              header: http.getHeader(),
              success: function (res) {
                uploadImgCount++;
                const data = JSON.parse(res.data);
                if (res.statusCode == 400) {
                  Taro.showToast({
                    title: data.message,
                    icon: 'none'
                  })
                  return
                }
                Taro.showToast({
                  title: '上传成功',
                  icon: 'none'
                })
                that.setState({tableFile: data.imageUrl, imgFile: null})
                //如果是最后一张,则隐藏等待中
                if (uploadImgCount == tempFilePaths.length) {
                  setTimeout(() => {
                    Taro.hideToast();
                  }, 2000)
                }
              },
              fail: function (res) {
                Taro.hideToast();
                Taro.showModal({
                  title: '错误提示',
                  content: '上传文件失败',
                  showCancel: false,
                  success: function (res) {
                  }
                })
              }
            });
          }
        }
      })
    }
  }

  async delLink() {
    this.setState({delModal: true})
    let teamAppoint = JSON.parse(Taro.getStorageSync('teamAppoint'))
    teamAppoint.splice(this.idx, 1)
    Taro.setStorageSync('teamAppoint', JSON.stringify(teamAppoint))
    Taro.showToast({title: '删除成功', icon: "none"})
    teamAppoint = JSON.parse(Taro.getStorageSync('teamAppoint'))
    this.setState({teamAppoint, delModal: false})
  }

  formGuide() {
    Taro.navigateTo({
      url: '/other/teamappoint/formGuide'
    })
  }

  // 大图预览
  maxImage(image) {
    Taro.previewImage({
      urls: [image]
    });
  }

  render() {
    const {
      minHeight,
      tableName,
      tableFile,
      delModal,
      teamAppoint,
      formData,
      radioStatus,
      isOpened,
      goodsMap,
      map,
      infoItemDetail,
      fieldCustom,
      imgFile
    } = this.state
    return (
      <View className='root confirm-root reserve-wrapper'>
        <GzhAuth />
        <View className='tu-reserve'>
          <View className='left-icon'>
            <AtIcon prefixClass='car' value='iconbowuguan' color='#fff' />
          </View>
          <View className='right-content'>
            {goodsMap.name}
          </View>
        </View>
        <View className='contact_box'>
          <AtForm className='person'>
            {infoItemDetail.reserve_date && <View className='item h5-reserve_date'>
              <Picker mode='date' value={formData.reserve_date} onChange={this.personInput.bind(this, 'reserve_date')}>
                <AtList>
                  <AtListItem className='require-date item-date' title='预约日期' extraText={formData.reserve_date} />
                </AtList>
              </Picker>
            </View>}
            {infoItemDetail.in_date &&
            <View className='item indate-range-item'>
              <Picker mode='time' value={formData.in_date} onChange={this.personInput.bind(this, 'in_date')}>
                <AtList>
                  <AtListItem className='require-date item-date' title='入场时间' extraText={formData.in_date} />
                </AtList>
              </Picker>
              <View className='indate-range'>{map.indate_start}-{map.indate_end}</View>
            </View>
            }
            {infoItemDetail.team_org && <View className='item'>
              <AtInput className='require' name='team_org' value={formData.team_org}
                onChange={this.personInput.bind(this, 'team_org')}
                type='text' title='组团单位' clear
              />
            </View>
            }
            {infoItemDetail.linkman && <View className='item'>
              <AtInput className='require' name='linkman' value={formData.linkman}
                onChange={this.personInput.bind(this, 'linkman')} type='text'
                title='领队姓名' maxLength={11} clear
              />
            </View>
            }
            {infoItemDetail.link_phone && <View className='item'>
              <AtInput className='require' name='link_phone' value={formData.link_phone}
                onChange={this.personInput.bind(this, 'link_phone')} type='number'
                title='领队电话' maxLength={11} clear
              />
            </View>
            }
            {infoItemDetail.team_address && <View className='item'>
              <AtInput className='require' name='team_address' value={formData.team_address}
                onChange={this.personInput.bind(this, 'team_address')} type='text'
                title='客源地' clear
              />
            </View>
            }
            {infoItemDetail.is_reserve_meal &&
            <View className='item is_reserve_meal'>
              <AtSwitch className='require' title='是否订餐' checked={formData.is_reserve_meal}
                onChange={this.personInput.bind(this, 'is_reserve_meal')}
              />
            </View>
            }
            {infoItemDetail.guide_num && <View className='item'>
              <AtInput className='require' name='guide_num' type='number'
                value={formData.guide_num} title='讲解员人数' clear maxLength={11}
                onChange={this.personInput.bind(this, 'guide_num')}
              />
            </View>
            }
            {infoItemDetail.custom_num && <View className='item' style='position: relative;'>
              <AtInput className='require' name='custom_num' type='number'
                value={formData.custom_num} title='预约人数' clear maxLength={3}
                onChange={this.personInput.bind(this, 'custom_num')}
              />
              {map.people_limit != 0 && <View className='indate-range'>
                人数{map.people_limit_start}-{map.people_limit_end}人
              </View>}
            </View>
            }
            {fieldCustom && fieldCustom.map(item =>
              <View className='item'>
                <AtInput clear className={`${item.ckd && 'require'}`} name={item.name} type='text'
                  value={formData[item.name]} title={item.k}
                  onChange={this.personInput.bind(this, item.name)}
                >
                </AtInput>
              </View>
            )}
          </AtForm>
        </View>
        <View className='xuan'>
          <View className='xuan-1' onClick={this.changeRadioStatus.bind(this, 0)}>
            <View className='round'>
              {radioStatus === 0 && <View className='round-content' />}
            </View>
            <View className='name'>添加游客</View>
          </View>
          <View className='xuan-2' onClick={this.changeRadioStatus.bind(this, 1)}>
            <View className='round'>
              {radioStatus === 1 && <View className='round-content' />}
            </View>
            <View className='name'>批量上传</View>
          </View>
        </View>
        {radioStatus === 0 &&
        <View className='tian' onClick={() => {
          if (map.people_limit === 1 && Number(map.people_limit_end) <= teamAppoint.length) return
          Taro.navigateTo({url: `/other/teamappoint/addcontact`})
        }}
        >
          <View className='add-tourist'>添加游客
            {Number(map.people_limit) === 1 &&
            <Text className='max-person'>人数{map.people_limit_start}-{map.people_limit_end}人</Text>}
          </View>
          <AtIcon value='add-circle' size='25' color='#ffbc43' />
        </View>
        }
        {radioStatus === 0 && teamAppoint.length > 0 &&
        <View className='tourist-info'>
          {teamAppoint.map((item, index) => <View className='tourist-info-item'>
            <View className='user-info'>
              <View onClick={() => {
                this.idx = index, this.setState({delModal: true})
              }}
              >
                <AtIcon className='san' value='subtract-circle' size='20' color='#ffbc43' />
              </View>
              <View className='user-content'>
                <View className='name'>{item.name}</View>
                <View className='number'>手机号：{item.phone}</View>
                {item.idcard && <View className='number'>证件号：{item.idcard}</View>}
              </View>
            </View>
            <View className='tourist-info-edit' onClick={() => {
              Taro.navigateTo({url: `/other/teamappoint/addcontact?idx=${index}`})
            }}
            >
              编辑
            </View>
          </View>)}
        </View>
        }
        {radioStatus === 1 &&
        <View className='upload-info'>
          {TARO_ENV !== 'h5' && <View className='upload' onClick={this.uploadFile.bind(this, 0)}><View
            className='upload-file'
          >上传表格</View><AtIcon prefixClass='car' value='iconshangchuanxiazai' size='25'
            color='#ffbc43'
          /></View>}
          <View className='upload' onClick={this.uploadFile.bind(this, 1)}><View
            className='upload-file'
          >上传图片</View><AtIcon prefixClass='car' value='iconhaibao1'
            size='25'
            color='#ffbc43'
          /></View>
        </View>
        }
        {
          radioStatus === 1 && imgFile && <View className='sizeImage' onClick={() => {
            this.maxImage(imgFile)
          }}
          >
            <Image src={imgFile} />
            <AtIcon value='add-circle' size='30' color='#fff' className='icon_circle'></AtIcon>
            <View className='close' onClick={(e) => {
              e.stopPropagation();
              this.setState({imgFile: null});
            }}
            >
              <AtIcon value='close' size='13'></AtIcon>
            </View>
          </View>
        }
        {
          radioStatus === 1 && tableFile && <View className='table'>
            <View className='table-item'>
              <AtIcon prefixClass='car' size='20' value='iconexcel' color='#1ab394' />
              <Text className='table-font'>
                {tableName}
              </Text>
            </View>
            <AtIcon onClick={() => this.setState({tableFile: null})} prefixClass='car' size='20'
              value='iconicon_tips_wrong' color='#8a8a8a'
            />
          </View>
        }
        {radioStatus === 1 && TARO_ENV !== 'h5' &&
        <View className='appointment-announcement'>
          <Text className='read' style='margin-right:0;'>*点击</Text>
          <Text className='announcement' onClick={this.downLoadFile.bind(this)}>表格模板</Text>
          <Text className='read' style='margin-right:0;'>并下载，点击查看</Text>
          <Text className='announcement' onClick={this.formGuide.bind(this)}>上传表格指南</Text>
        </View>}
        <View className='appointment-announcement'>
          <Text className='read'>*请仔细阅读</Text>
          <Text className='announcement' onClick={() => {
            this.setState({isOpened: true})
          }}
          >预约公告</Text>
        </View>
        {isOpened && <AtModal className='model' isOpened={isOpened} onClose={() => {
          this.setState({isOpened: false})
        }}
        >
          <AtModalHeader>预约须知<AtIcon onClick={() => {
            this.setState({isOpened: false})
          }} className='close-cla' value='close' size='20' color='#888888'
          /></AtModalHeader>
          <View className='w-b-ba'>
            <ScrollView
              style={`min-height:${minHeight + 'px'};max-height:${minHeight + 'px'}`}
              className='scrollView'
              scrollY
            >
              {process.env.TARO_ENV === "weapp" && <parser selectable html={map.attention_need || ''} />}
              {process.env.TARO_ENV === "tt" && <rich-text preview selectable nodes={getContent(map.attention_need)} />}
              {process.env.TARO_ENV === "h5" && !!map.attention_need &&
              <View dangerouslySetInnerHTML={{__html: map.attention_need}} />}
            </ScrollView>
          </View>
          <AtModalAction><Button onClick={() => {
            this.setState({isOpened: false})
          }} className='readed'
          >已阅读并确定</Button></AtModalAction>
        </AtModal>}
        <View className='detailBar zindex'>
          <View className='service-box'>
            <View className='service-item goto-home' style='border-right:1px solid #ddd' onClick={() => {
              Taro.switchTab({url: '/pages/index/index'})
            }}
            >
              <View className='home'><Image className='img'
                src={RESOURCE_URL + "/resources/weapp/images/detail-home.png"}
                mode='aspectFit'
              /></View>
              <View className='text'>首页</View>
            </View>
            <View className='service-item goto-service' onClick={() => {
              Taro.navigateTo({url: `/distributor/contact/contact`})
            }}
            >
              <View className='kefu'><Image className='img'
                src={RESOURCE_URL + "/resources/weapp/images/detail-kefu.png"}
                mode='aspectFit'
              /></View>
              <View className='text'>客服</View>
            </View>
          </View>
          <View className='btn-box btn-box-reserve' onClick={this.confirmReserve.bind(this)}>
            <Button className='btn'>立即预约</Button>
          </View>
        </View>
        <AtModal
          isOpened={delModal}
          cancelText='取消'
          confirmText='确认'
          onClose={() => {
            this.setState({delModal: false})
          }}
          onCancel={() => {
            this.setState({delModal: false})
          }}
          onConfirm={this.delLink.bind(this)}
          content='是否确定删除?'
        />
      </View>
    )
  }
}

export default Confirm as ComponentClass<PageOwnProps, PageState>
